<template>
  <!-- PayDetail 缴费详情页 -->
  <PageContainer>
    <view class="container">
      <Header :title="pageTitle" :is-box-shadow="false" />
      <BasicsForm
        v-if="info || memberName"
        :disabled="!isEdit"
        :show-placeholder-view="false"
        @register="formRegister"
        :btn-group-options="
          isEdit
            ? {
                submit: {
                  text: '确认缴费',
                },
              }
            : {}
        "
        @submit="onSubmit"
      />
      <view class="disFlx">
        <view>
          <view class="fz-14 flexBox">
            <image src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/icon/warning.png" style="width: 40rpx; height: 40rpx"></image>
            <text class="pl-4">缴费函</text>
          </view>
          <view class="fz-12 color8 mt-10">
            <text>下载缴费函,通知用户缴费</text>
          </view>
        </view>
        <button type="none" class="btn" @click="handleDownload">缴费函</button>
      </view>

      <ShowModal
        v-model="visible"
        content="审核通过,已缴费"
        cancelText="返回审核列表"
        confirmText="查看会员证"
        @close="handleClose"
        @confirm="handleConfirm"
      ></ShowModal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  PayDetail  缴费详情页 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import ShowModal from '@/components/ShowModal/index.vue';
  import { navigateBack, navigateTo, onLoad, redirectTo } from '@/router';
  import { ref } from 'vue';
  import { paymentRecordInfo, Api, memberApplyPayment } from '@/api/admin';
  import { type FormActionType, type FormSchema, useForm } from '@/components/Form';
  import { useEnv } from '@/hooks/core/useEnv';
  import { useUpload } from '@/hooks/core/useUpload';

  const id = ref();
  const isEdit = ref(false);
  const memberName = ref();
  const levelName = ref();
  const membershipFees = ref();
  const info = ref();
  const visible = ref();
  const pageTitle = ref('缴费详情页');
  let callback: () => void;
  onLoad<'PayDetail'>((op) => {
    console.log(op);
    id.value = op.id;
    memberName.value = op.memberName;
    levelName.value = op.levelName;
    membershipFees.value = op.membershipFees;
    isEdit.value = op.isEdit;
    callback = op.callback as any;
    if (!isEdit.value) {
      getInfo();
    } else {
      pageTitle.value = '人工缴费';
    }
  });

  const getInfo = async () => {
    let res = await paymentRecordInfo(id.value);
    info.value = res;
  };

  const schemas = ref<FormSchema[]>([
    {
      field: 'memberName',
      label: '会员名称',
      component: 'Input',
    },
    {
      field: 'nowLevelName',
      label: '会员职务',
      component: 'Input',
    },
    {
      field: 'nowMoney',
      label: '缴纳金额(元)',
      required: true,
      component: 'Input',
    },
    {
      field: 'time',
      label: '当前缴费时间',
      required: true,
      component: 'DatePicker',
    },
    {
      field: 'endTime',
      label: '本期缴费至',
      required: true,
      component: 'DatePicker',
    },
    {
      field: 'paymentVoucher',
      label: '缴费凭证',
      component: 'UploadImg',
      componentProps: {
        limit: 1,
      },
    },
    {
      field: 'remarks',
      label: '备注',
      component: 'InputTextArea',
    },
  ]);

  const [register, { updateSchema, appendSchemaByField, setFieldsValue }] = useForm({
    labelAlign: 'left',
    validateTrigger: 'bind',
    labelWidth: 120,
    schemas: schemas,
  });

  function formRegister(instance: FormActionType) {
    register(instance);
    if (info.value) {
      for (let i = 0; i < schemas.value.length; i++) {
        const item = schemas.value[i];
        updateSchema({
          field: item.field,
          required: false,
          defaultValue: info.value[item.field],
        });
      }
    } else {
      updateSchema([
        {
          field: 'memberName',
          dynamicDisabled: true,
          defaultValue: memberName.value,
        },
        {
          field: 'levelName',
          dynamicDisabled: true,
          defaultValue: levelName.value,
        },
        {
          field: 'money',
          defaultValue: membershipFees.value,
        },
      ]);
    }
  }

  // 下载缴费函
  const { getEnv } = useEnv();
  const { openDocument } = useUpload();
  const handleDownload = () => {
    const url =
      getEnv('BASE_URL') + Api[isEdit.value ? 'mafPaymentExport' : 'paymentExport'] + id.value;
    openDocument({ filePath: url, fileType: 'pdf' });
  };

  const memberIdRef = ref<number>();
  const onSubmit = (data: any) => {
    console.log('data--->', data);
    memberApplyPayment({
      memberId: id.value,
      membershipFees: data.money,
      startTime: data.time,
      endTime: data.endTime,
      paymentVoucher: data.paymentVoucher,
      remarks: data.remarks,
      // levelId: 13,
    }).then(({ memberId }) => {
      memberIdRef.value = memberId;
      success();
    });
  };

  const success = () => {
    visible.value = true;
  };

  const handleClose = () => {
    callback?.();
    redirectTo({ name: 'memberAudit' });
  };

  const handleConfirm = () => {
    callback?.();
    memberIdRef.value && navigateTo({ name: 'membershipCard', options: { id: memberIdRef.value } });
  };
</script>

<style lang="scss" scoped>
  .container {
    background-color: #fff;
    padding-top: 30rpx;
  }

  .disFlx {
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    height: 130rpx;
    padding: 20rpx 30rpx;
    background-color: #fff;
    margin-top: 30rpx;
    padding-bottom: 200rpx;
    .color8 {
      color: #808080;
    }

    .btn {
      background-color: #e9e3b5;
      color: #000;
      width: 140rpx;
      height: 60rpx;
      line-height: 60rpx;
      text-align: center;
      font-size: 28rpx;
      border-radius: 8rpx;
      box-sizing: border-box;
    }
  }

  .flexBox {
    display: flex;
    align-items: center;
  }
</style>
